<template>
  <div class="profile-page">
    <div class="page-header">
      <el-button type="primary" :icon="Edit" @click="handleEdit">
        编辑资料
      </el-button>
    </div>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="never">
          <template #header>
            <span>基本信息</span>
          </template>

          <el-descriptions :column="2" border>
            <el-descriptions-item label="姓名">
              {{ profileData.name || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="昵称">
              {{ profileData.nickname || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="职位">
              {{ profileData.position || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="邮箱">
              {{ profileData.email || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="电话">
              {{ profileData.phone || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="所在城市">
              {{ profileData.city || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="工作年限">
              {{ profileData.workYears || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="个人简介" :span="2">
              {{ profileData.bio || '这个人很懒，什么都没有留下...' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>

    <!-- 编辑资料弹窗 -->
    <el-dialog v-model="editFormVisible" title="编辑个人资料" width="700px" @close="resetForm">
      <el-form ref="profileFormRef" :model="profileForm" :rules="formRules" label-width="120px" status-icon>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="profileForm.name" placeholder="请输入真实姓名" maxlength="100" />
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="profileForm.nickname" placeholder="请输入昵称（显示名称）" maxlength="100" />
        </el-form-item>

        <el-form-item label="职位" prop="position">
          <el-input v-model="profileForm.position" placeholder="请输入职位" maxlength="255" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email" placeholder="请输入邮箱" type="email" />
        </el-form-item>

        <el-form-item label="电话" prop="phone">
          <el-input v-model="profileForm.phone" placeholder="请输入电话号码" maxlength="20" />
        </el-form-item>

        <el-form-item label="所在城市" prop="city">
          <el-input v-model="profileForm.city" placeholder="请输入所在城市" maxlength="100" />
        </el-form-item>

        <el-form-item label="工作年限" prop="workYears">
          <el-input v-model="profileForm.workYears" placeholder="例如：5年" maxlength="50" />
        </el-form-item>

        <el-form-item label="个人简介" prop="bio">
          <el-input v-model="profileForm.bio" type="textarea" :rows="4" placeholder="请输入个人简介" maxlength="2000" show-word-limit />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Edit } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { personalProfileApi } from '@/utils/api'

// 响应式数据
const editFormVisible = ref(false)
const profileFormRef = ref()
const loading = ref(false)

// 个人资料数据
const profileData = reactive({
  id: null,
  name: '',
  nickname: '',
  position: '',
  email: '',
  phone: '',
  city: '',
  workYears: '',
  bio: ''
})

// 编辑表单数据
const profileForm = reactive({
  name: '',
  nickname: '',
  position: '',
  email: '',
  phone: '',
  city: '',
  workYears: '',
  bio: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 1, max: 100, message: '姓名长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  nickname: [
    { max: 100, message: '昵称不能超过 100 个字符', trigger: 'blur' }
  ],
  position: [
    { required: true, message: '请输入职位', trigger: 'blur' },
    { min: 1, max: 255, message: '职位长度在 1 到 255 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { min: 6, max: 20, message: '电话号码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  city: [
    { required: true, message: '请输入所在城市', trigger: 'blur' },
    { max: 100, message: '所在城市不能超过 100 个字符', trigger: 'blur' }
  ],
  workYears: [
    { required: true, message: '请输入工作年限', trigger: 'blur' },
    { max: 50, message: '工作年限不能超过 50 个字符', trigger: 'blur' }
  ],
  bio: [
    { required: true, message: '请输入个人简介', trigger: 'blur' },
    { max: 2000, message: '个人简介不能超过 2000 个字符', trigger: 'blur' }
  ]
}

// 方法
const handleEdit = () => {
  initFormData()
  editFormVisible.value = true
}

// 加载个人信息数据
const loadProfileData = async () => {
  try {
    loading.value = true
    // 使用公开接口获取个人信息
    const response = await personalProfileApi.getPublicProfile()
    if (response.code === 0) {
      const profile = response.data
      profileData.id = profile.id
      profileData.name = profile.name || ''
      profileData.nickname = profile.nickname || ''
      profileData.position = profile.position || ''
      profileData.email = profile.email || ''
      profileData.phone = profile.phone || ''
      profileData.city = profile.city || ''
      profileData.workYears = profile.workYears || ''
      profileData.bio = profile.bio || ''
    } else {
      ElMessage.error(response.message || '加载个人信息失败')
    }
  } catch (error) {
    console.error('加载个人信息失败:', error)
    ElMessage.error('加载个人信息失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  if (!profileFormRef.value) return

  try {
    await profileFormRef.value.validate()

    if (!profileData.id) {
      ElMessage.error('个人信息数据未加载')
      return
    }

    // 调用API保存数据到后端
    const response = await personalProfileApi.update(profileData.id, {
      name: profileForm.name.trim(),
      nickname: profileForm.nickname?.trim() || '',
      position: profileForm.position.trim(),
      email: profileForm.email.trim(),
      phone: profileForm.phone.trim(),
      city: profileForm.city.trim(),
      workYears: profileForm.workYears.trim(),
      bio: profileForm.bio.trim()
    })

    if (response.code === 0) {
      // 更新本地数据
      Object.assign(profileData, profileForm)
      editFormVisible.value = false
      ElMessage.success('个人资料保存成功')
      // 重新加载数据
      loadProfileData()
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

const resetForm = () => {
  if (profileFormRef.value) {
    profileFormRef.value.resetFields()
  }
}

// 初始化表单数据
const initFormData = () => {
  Object.assign(profileForm, profileData)
}

// 在组件挂载时初始化数据
onMounted(() => {
  loadProfileData()
})
</script>

<style scoped>
.profile-page {
  padding: 0;
}

/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

/* 弹窗样式 */
.el-dialog {
  border-radius: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表单样式 */
.el-form-item {
  margin-bottom: 18px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  padding-left: 4px;
}
</style>